package cn.codenest.rabbitmqbootpublisher.util.impl;

import cn.codenest.rabbitmqbootpublisher.callback.MyConfirmCallback;
import cn.codenest.rabbitmqbootpublisher.callback.MyReturnCallback;
import cn.codenest.rabbitmqbootpublisher.util.RbmqService;
import com.rabbitmq.client.ShutdownSignalException;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.amqp.AmqpConnectException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.locks.LockSupport;

/**
 * @author ：Hyman
 * @date ：Created in 2021/7/6 19:33
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class RbmqServiceImpl implements RbmqService {

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public void sendMsg(String str) {
        try {
            Message message = new Message(str.getBytes());
            rabbitTemplate.setConfirmCallback(new MyConfirmCallback());
            rabbitTemplate.setMandatory(true);
            rabbitTemplate.setReturnsCallback(new MyReturnCallback());
            rabbitTemplate.send("TestDirectExchange", "TestDirectQueue", message);
            User user = new User("张三", 18);
            rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectQueue", user);
        }  catch (ShutdownSignalException e) {
            System.out.println("交换机故障或者不存在。");
            e.printStackTrace();
        }catch (AmqpConnectException e) {
            System.out.println("服务器连接失败。");
            e.printStackTrace();
        }

    }
}

@Data
@AllArgsConstructor
class User implements Serializable {

    private static final long serialVersionUID = 1L;

    String name;
    int age;
}
